import React, { useCallback, useEffect, useState } from 'react';
import { useDispatch } from 'react-redux';
import { Route, Routes, useNavigate } from 'react-router-dom';
import _ from 'underscore';

import PrivateRoute from '@/hooks/PrivateRoute';
import Loading from '@/components/Loading';
import { routers, addDynamicRoute } from "@/router";
import { flatRoutes } from '@/utils/routeUtils';
import LayoutLoader from '@/layout';
import { NOTFOUND } from '@/config/url';
import { getGrid } from '@/utils';
import { validate } from '@/service';
import Cookies from "js-cookie";
import { setUserInfo, setLoginOpen } from '@/reducers/main';
import { useTranslation } from 'react-i18next';

function Application(props) {
    const baseRouters = routers();
    const { t } = useTranslation();
    const initState = () => ({
        loading: true,
        routerTree: baseRouters,
        routers: flatRoutes(baseRouters),
    }),
        [state, setState] = useState(initState),
        dispatch = useDispatch();
    const navigate = useNavigate();
    /**
     * 检查用户是否登录（也可以获取用户信息）
     *
     */
    const checkLogged = () => {
        let routes = state.routers || [],
            authSource = [], // 后端返回的数据
            authRoutes = addDynamicRoute(authSource), // 这里需要传入后端返回的数据
            appRoutes = flatRoutes(routes.concat(authRoutes)), // 应用的所有路由
            routerTree = baseRouters.concat(authSource); // 原始路由数据
        window.SITE_CONFIG['appRouterTree'] = routerTree;
        window.SITE_CONFIG['appRouteArray'] = appRoutes;
        setState(o => ({
            ...o,
            routers: appRoutes,
            routerTree,
            loading: false,
        }));
        validate().then(response => {
            let { code } = response || {};
            setState(o => ({
                ...o,
                loading: false,
            }));
            if (code !== 0) {
                clearInfo();
                navigate(`${BASEDIR}/login`);
            } else {
                const token = data?.token;
                const expire = data?.expire;
                const user = data?.user || {};
                Cookies.set('aws_phase_token', token, { expires: expire });
                dispatch(setUserInfo(user));
                localStorage.setItem("aws_phase_userinfo", JSON.stringify(user));
            }
        }).catch(e => {
            setState(o => ({
                ...o,
                loading: false,
            }));
        });
    };
    const clearInfo = () => {
        Cookies.remove('aws_phase_token');
        // localStorage.removeItem('language');
        dispatch(setUserInfo({}));
        localStorage.removeItem("aws_phase_userinfo");
    }

    /**
     * 监听页面宽度变化
     *
     */
    const resizeListen = useCallback(() => {
        let grid = getGrid();
        // dispatch(setStore({
        //     grid,
        //     isMobile: isMobileApp(grid),
        //     isPad: isPadApp(grid),
        //     isPc: isPcApp(grid),
        // }));
    }, []);

    // 这是入口文件，页面间切换不会触发，只有应用首次加载时才会触发
    useEffect(() => {
        // 判断是否登录
        checkLogged();
        // 先执行一次屏幕宽度计算
        resizeListen();
        // 监听页面宽度变化，节流
        const handleResize = _.throttle(resizeListen, 200);
        window.addEventListener('resize', handleResize, false);
        return () => {
            window.removeEventListener('resize', handleResize, false);
        }
    }, []);
    return (
        <>
            {state.loading ? (
                <Loading tip={t('common.loading.tipTwo')} />
            ) : (
                <LayoutLoader routerTree={state.routerTree || []}>
                    <Routes>
                        {(state.routers || []).map(item => (
                            <Route
                                key={item.url}
                                path={item.url}
                                element={<PrivateRoute element={item.component} />}
                            />
                        ))}
                        <Route
                            path="*"
                            element={<PrivateRoute element={baseRouters.find(i => i.url === NOTFOUND)?.component || null} />}
                        />
                    </Routes>
                </LayoutLoader>
            )}
        </>
    );
}

export default Application;


